from random import random

from django.contrib.auth.decorators import login_required
from django.contrib.sites import requests
from django.core.exceptions import ObjectDoesNotExist
from django.utils import timezone

from django.db.models import Q
from django.http import JsonResponse, HttpResponse, HttpResponseForbidden
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt, ensure_csrf_cookie
from django.views.decorators.http import require_http_methods
from rest_framework import generics, status, permissions
from rest_framework.decorators import api_view
from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView
from rest_framework.pagination import PageNumberPagination
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
import json
from django.middleware.csrf import get_token
from rest_framework.views import APIView
import requests
from .models import QaPair, ScenicSpot, Admin, Submitter, DataTicket, TouristAttraction
from .serializers import QaPairSerializer, ScenicSpotSerializer, AdminSerializer, DataTicketSerializer, \
    SubmitterSerializer
from django.contrib.auth.hashers import make_password, check_password
#问答对管理函数
#分页器实现数据
class StandardResultsSetPagination(PageNumberPagination):
    page_size = 10
    page_size_query_param = 'limit'
    max_page_size = 1000
    page_query_param = 'page'
# 删除问答对
class QaPairRetrieveUpdateDestroy(RetrieveUpdateDestroyAPIView):
    queryset = QaPair.objects.all()
    serializer_class = QaPairSerializer

#查询问答对
class StandardResultsSetPagination(PageNumberPagination):
    page_size = 10
    page_size_query_param = 'limit'
    max_page_size = 100

class QaPairListCreate(ListCreateAPIView):
    queryset = QaPair.objects.all()
    pagination_class = StandardResultsSetPagination
    serializer_class = QaPairSerializer
    def get_queryset(self):
        queryset = super().get_queryset()
        keyword = self.request.query_params.get('keyword', None)
        if keyword:
            queryset = queryset.filter(Q(question__icontains=keyword) | Q(answer__icontains=keyword))
        return queryset.distinct()

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

@api_view(['POST'])
def add_qa_pair(request):
    if request.method == 'POST':
        serializer = QaPairSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            scenic_spot = ScenicSpot.objects.get(jq_id=serializer.validated_data['jq'].jq_id)
            scenic_spot.qa_count += 1
            scenic_spot.save()
            print(serializer.data)
            return Response(serializer.data, status=201)
        else:
            return Response(serializer.errors, status=400)
    else:
        return JsonResponse({'error': 'Only POST method is allowed'}, status=405)


@csrf_exempt  #允许跨域请求，但仍然需要在前端发送 CSRF 令牌
@require_http_methods(["OPTIONS", "DELETE"])
def delete_qa_pair(request, qa_id):
    if request.method == 'OPTIONS':
        response = JsonResponse({'message': 'OPTIONS request'})
        response['Access-Control-Allow-Origin'] = 'http://localhost:5173'
        response['Access-Control-Allow-Methods'] = 'DELETE'
        response['Access-Control-Allow-Headers'] = 'Content-Type, X-CSRFToken'
        response['Access-Control-Allow-Credentials'] = 'true'
        response['Access-Control-Max-Age'] = '86400'  # 预检请求的有效期，单位为秒
        return response

    csrf_token = get_token(request)
    response = JsonResponse({'message': '问答对删除成功', 'csrf_token': csrf_token})
    response['Access-Control-Allow-Origin'] = 'http://localhost:5173'
    response['Access-Control-Allow-Credentials'] = 'true'

    try:
        qa_pair = QaPair.objects.get(qa_id=qa_id)
        scenic_spot = qa_pair.jq
        scenic_spot.qa_count -= 1
        scenic_spot.save()
        qa_pair.delete()
        return response
    except QaPair.DoesNotExist:
        response.status_code = 404
        response.content = JsonResponse({'error': '问答对不存在'}).content
        return response

@csrf_exempt
@require_http_methods(["PUT"])
def update_qa_pair(request, qa_id):
    try:
        qa_pair = QaPair.objects.get(qa_id=qa_id)
    except QaPair.DoesNotExist:
        return JsonResponse({'error': '问答对不存在'}, status=404)
    data = json.loads(request.body)
    # 更新问答对信息
    if 'question' in data:
        qa_pair.question = data['question']
    if 'answer' in data:
        qa_pair.answer = data['answer']
    if 'jq_id' in data:
        qa_pair.jq_id = data['jq_id']
    qa_pair.last_operation_time = timezone.now()
    qa_pair.save()
    return JsonResponse({'message': '问答对更新成功'})


#景区管理函数
#查询进去管理函数
class ScenicSpotListCreateAPIView(generics.ListCreateAPIView):
    queryset = ScenicSpot.objects.all()
    pagination_class = StandardResultsSetPagination
    serializer_class = ScenicSpotSerializer
    def get_queryset(self):
        queryset = super().get_queryset()
        keyword = self.request.query_params.get('keyword', None)
        if keyword:
            queryset = queryset.filter(Q(jq_name__icontains=keyword) | Q(jq_address__icontains=keyword))
        return queryset.distinct()

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)
#进行添加景区函数

@api_view(['POST'])
def add_scenic_spot(request):
    if request.method == 'POST':
        serializer = ScenicSpotSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    else:
        return Response({'error': 'Only POST method is allowed'}, status=status.HTTP_405_METHOD_NOT_ALLOWED)

#进行修改景区函数
@csrf_exempt
@require_http_methods(["PUT"])
def update_scenic_spot(request, jq_id):
    try:
        scenic_spot = ScenicSpot.objects.get(jq_id=jq_id)
    except ScenicSpot.DoesNotExist:
        return JsonResponse({'error': '景点不存在'}, status=404)
    data = json.loads(request.body)
    #更新景点信息
    if 'jq_name' in data:
        scenic_spot.jq_name = data['jq_name']
    if 'jq_city' in data:
        scenic_spot.jq_city = data['jq_city']
    if 'jq_address' in data:
        scenic_spot.jq_address = data['jq_address']
    if 'jq_rating' in data:
        scenic_spot.jq_rating = data['jq_rating']
    if 'jq_type' in data:
        scenic_spot.jq_type = data['jq_type']
    if 'qa_count' in data:
        scenic_spot.qa_count = data['qa_count']
    if 'responsible_admin' in data:
        try:
            admin = Admin.objects.get(admin_id=data['responsible_admin'])
            scenic_spot.responsible_admin = admin
        except Admin.DoesNotExist:
            return JsonResponse({'error': '管理员不存在'}, status=404)
    scenic_spot.last_operation_time = timezone.now()
    scenic_spot.save()
    return JsonResponse({'message': '景点信息更新成功'})

#进行删除景区函数
@csrf_exempt
@require_http_methods(["OPTIONS", "DELETE"])
def delete_scenic_spot(request, jq_id):
    if request.method == 'OPTIONS':
        response = JsonResponse({'message': 'OPTIONS request'})
        response['Access-Control-Allow-Origin'] = 'http://localhost:5173'
        response['Access-Control-Allow-Methods'] = 'DELETE'
        response['Access-Control-Allow-Headers'] = 'Content-Type, X-CSRFToken'
        response['Access-Control-Allow-Credentials'] = 'true'
        response['Access-Control-Max-Age'] = '86400'  # 预检请求的有效期，单位为秒
        return response
    csrf_token = get_token(request)
    response = JsonResponse({'message': '景点删除成功', 'csrf_token': csrf_token})
    response['Access-Control-Allow-Origin'] = 'http://localhost:5173'
    response['Access-Control-Allow-Credentials'] = 'true'
    try:
        scenic_spot = ScenicSpot.objects.get(jq_id=jq_id)
        scenic_spot.delete()
        return response
    except ScenicSpot.DoesNotExist:
        response.status_code = 404
        response.content = JsonResponse({'error': '景点不存在'}).content
        return response
#管理者管理函数

class AdminListCreateAPIView(generics.ListCreateAPIView):
    queryset = Admin.objects.all()
    pagination_class = StandardResultsSetPagination
    serializer_class = AdminSerializer
    def get_queryset(self):
        queryset = super().get_queryset()
        keyword = self.request.query_params.get('keyword', None)
        if keyword:
            queryset = queryset.filter(Q(admin_id__icontains=keyword) | Q(responsible_scenic_id__icontains=keyword))
        return queryset.distinct()

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)


class SubmitterListCreateAPIView(generics.ListCreateAPIView):
    queryset = Submitter.objects.all()
    pagination_class = StandardResultsSetPagination
    serializer_class = SubmitterSerializer
    def get_queryset(self):
        queryset = super().get_queryset()
        keyword = self.request.query_params.get('keyword', None)
        if keyword:
            queryset = queryset.filter(Q(submitter_id__icontains=keyword))
        return queryset.distinct()

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

@api_view(['POST'])
def add_submitter(request):
    if request.method == 'POST':
        serializer = SubmitterSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    else:
        return Response({'error': 'Only POST method is allowed'}, status=status.HTTP_405_METHOD_NOT_ALLOWED)





@api_view(['POST'])
def add_scenic_spot1(request):
    if request.method == 'POST':
        serializer =  AdminSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    else:
        return Response({'error': 'Only POST method is allowed'}, status=status.HTTP_405_METHOD_NOT_ALLOWED)


@csrf_exempt
@require_http_methods(["PUT"])
def update_submitter(request, submitter_id):
    try:
        submitter = Submitter.objects.get(submitter_id=submitter_id)
    except Submitter.DoesNotExist:
        return JsonResponse({'error': '提交者不存在'}, status=404)
    data = json.loads(request.body)
    if 'submitter_pass' in data:
        submitter.submitter_pass = data['submitter_pass']
    if 'submitted_tickets' in data:
        submitter.submitted_tickets = data['submitted_tickets']
    if 'flag' in data:
        submitter.flag = data['flag']
    submitter.save()

    return JsonResponse({'message': '提交者信息更新成功'})

@csrf_exempt
@require_http_methods(["PUT"])
def update_admin(request, admin_id):
    try:
        admin = Admin.objects.get(admin_id=admin_id)
    except Admin.DoesNotExist:
        return JsonResponse({'error': '管理员不存在'}, status=404)

    data = json.loads(request.body)
    # 更新管理员信息
    if 'admin_pass' in data:
        admin.admin_pass = data['admin_pass']
    if 'responsible_scenic_id' in data:
        admin.responsible_scenic_id = data['responsible_scenic_id']
    if 'submitted_tickets' in data:
        admin.submitted_tickets = data['submitted_tickets']
    admin.last_operation_time = timezone.now()
    admin.save()
    return JsonResponse({'message': '管理员信息更新成功'})




@csrf_exempt
@require_http_methods(["OPTIONS", "DELETE"])
def delete_scenic_spot1(request, admin_id):
    if request.method == 'OPTIONS':
        response = JsonResponse({'message': 'OPTIONS request'})
        response['Access-Control-Allow-Origin'] = 'http://localhost:5173'
        response['Access-Control-Allow-Methods'] = 'DELETE'
        response['Access-Control-Allow-Headers'] = 'Content-Type, X-CSRFToken'
        response['Access-Control-Allow-Credentials'] = 'true'
        response['Access-Control-Max-Age'] = '86400'  #
        return response
    csrf_token = get_token(request)
    response = JsonResponse({'message': '管理员删除成功', 'csrf_token': csrf_token})
    response['Access-Control-Allow-Origin'] = 'http://localhost:5173'
    response['Access-Control-Allow-Credentials'] = 'true'
    try:
        scenic_spot =  Admin.objects.get(admin_id=admin_id)
        scenic_spot.delete()
        return response
    except Admin.DoesNotExist:
        response.status_code = 404
        response.content = JsonResponse({'error': '管理员不存在'}).content
        return response

@csrf_exempt
@require_http_methods(["OPTIONS", "DELETE"])
def delete_submitter(request, submitter_id):
    if request.method == 'OPTIONS':
        response = JsonResponse({'message': 'OPTIONS request'})
        response['Access-Control-Allow-Origin'] = 'http://localhost:5173'
        response['Access-Control-Allow-Methods'] = 'DELETE'
        response['Access-Control-Allow-Headers'] = 'Content-Type, X-CSRFToken'
        response['Access-Control-Allow-Credentials'] = 'true'
        response['Access-Control-Max-Age'] = '86400'  # 1 day
        return response
    csrf_token = get_token(request)
    response = JsonResponse({'message': '提交者删除成功', 'csrf_token': csrf_token})
    response['Access-Control-Allow-Origin'] = 'http://localhost:5173'
    response['Access-Control-Allow-Credentials'] = 'true'
    try:
        submitter = Submitter.objects.get(submitter_id=submitter_id)
        submitter.delete()
        return response
    except Submitter.DoesNotExist:
        response.status_code = 404
        response.content = JsonResponse({'error': '提交者不存在'}).content
        return response


@csrf_exempt
@require_http_methods(["POST"])
def register(request):
    data = json.loads(request.body)
    submitter_id = data.get('submitter_id')
    submitter_pass = data.get('submitter_pass')
    print(submitter_id)
    print(submitter_pass)
    if not submitter_id or not submitter_pass:
        return JsonResponse({'message': '所有字段都不能为空'}, status=400)
    if Admin.objects.filter(admin_id=submitter_id).exists() or Submitter.objects.filter(submitter_id=submitter_id).exists():
        return JsonResponse({'message': '账号ID已存在'}, status=400)
    submitter = Submitter.objects.create(
        submitter_id=submitter_id,
        submitter_pass=submitter_pass
    )
    return JsonResponse({'message': '注册成功', 'token': 'your_token_here'}, status=201)


# @csrf_exempt
# @require_http_methods(["POST"])
# def login(request):
#     data = json.loads(request.body)
#     submitter_id = data.get('submitter_id')
#     submitter_pass = data.get('submitter_pass')
#     submitter = Submitter.objects.get(submitter_id='S0001')
#     if not submitter_id or not submitter_pass:
#         return JsonResponse({'message': '所有字段都不能为空'}, status=400)
#     submitter = Submitter.objects.filter(submitter_id=submitter_id).first()
#     if not submitter:
#         return JsonResponse({'message': '账号不存在'}, status=400)
#     print(submitter.submitter_pass)
#     if not check_password(submitter_pass, submitter.submitter_pass):
#         return JsonResponse({'message': '账号或密码错误'}, status=400)
#     print(2)
#     submitter.last_operation_time = timezone.now()
#     submitter.save()
#     return JsonResponse({'message': '登录成功', 'token': 'your_token_here'}, status=200)

# @csrf_exempt
# @require_http_methods(["POST"])
# def login(request):
#     data = json.loads(request.body)
#     user_id = data.get('submitter_id')
#     user_pass = data.get('submitter_pass')
#     if not user_id or not user_pass:
#         return JsonResponse({'message': '所有字段都不能为空'}, status=400)
#     admin = Admin.objects.filter(admin_id=user_id).first()
#     if admin and admin.admin_pass == user_pass:
#         role = 'admin' if admin.flag == 1 else 'submitter'
#         user = admin
#         return JsonResponse({'message': '登录成功', 'role': role, 'token': 'your_token_here'}, status=200)
#     submitter = Submitter.objects.filter(submitter_id=user_id).first()
#     if submitter and submitter.submitter_pass == user_pass:
#         role = 'admin' if submitter.flag == 1 else 'submitter'
#         user = submitter
#     else:
#         return JsonResponse({'message': '账号不存在或账号或密码错误'}, status=400)
#     user.last_operation_time = timezone.now()
#     user.save()
#     return JsonResponse({'message': '登录成功', 'role': role, 'token': 'your_token_here'}, status=200)


@csrf_exempt
@require_http_methods(["POST"])
def login(request):
    data = json.loads(request.body)
    user_id = data.get('submitter_id')
    user_pass = data.get('submitter_pass')
    if not user_id or not user_pass:
        return JsonResponse({'message': '所有字段都不能为空'}, status=400)
    admin = Admin.objects.filter(admin_id=user_id).first()
    if admin and admin.admin_pass == user_pass:
        role = 'admin' if admin.flag == 1 else 'submitter'
        user = admin
        return JsonResponse({'message': '登录成功', 'role': role, 'token': 'your_token_here','submitter_id':user_id}, status=200)
    submitter = Submitter.objects.filter(submitter_id=user_id).first()
    if submitter and submitter.submitter_pass == user_pass:
        role = 'admin' if submitter.flag == 1 else 'submitter'
        user = submitter
        user_id = submitter.submitter_id  #获取提交者账号
    else:
        return JsonResponse({'message': '账号不存在或账号或密码错误'}, status=400)
    user.last_operation_time = timezone.now()
    user.save()
    return JsonResponse({
        'message': '登录成功',
        'role': role,
        'submitter_id': user_id,  #
        'token': 'your_token_here'
    }, status=200)



class DataTicketCreateView(APIView):
    def post(self, request, format=None):
        serializer = DataTicketSerializer(data=request.data)
        print(serializer)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data, status=status.HTTP_201_CREATED)
        return JsonResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


class DataTicketListView(generics.ListCreateAPIView):
    serializer_class = DataTicketSerializer
    pagination_class = StandardResultsSetPagination
    def get_queryset(self):
        submitter_id = self.request.query_params.get('submitter_id', None)
        print(submitter_id)
        if not submitter_id:
            return DataTicket.objects.none()
        queryset = DataTicket.objects.filter(submitter__submitter_id=submitter_id)
        keyword = self.request.query_params.get('keyword', None)
        if keyword:
            queryset = queryset.filter(
                Q(ticket_type__icontains=keyword) |
                Q(question__icontains=keyword) |
                Q(answer__icontains=keyword) |
                Q(status__icontains=keyword)
            )
        return queryset.distinct()
    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        print(queryset)
        if not queryset.exists():
            return Response({'message': '没有数据'}, status=status.HTTP_200_OK)

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

@csrf_exempt
@require_http_methods(["PUT"])
def update_data_ticket(request, ticket_id):
    try:
        data_ticket = DataTicket.objects.get(ticket_id=ticket_id)
    except ObjectDoesNotExist:
        return JsonResponse({'error': 'DataTicket not found'}, status=404)
    import json
    data = json.loads(request.body)
    data_ticket.ticket_type = data.get('ticket_type', data_ticket.ticket_type)
    data_ticket.question = data.get('question', data_ticket.question)
    data_ticket.answer = data.get('answer', data_ticket.answer)
    submitter_id = data.get('submitter_id')
    data_ticket.submit_count=data_ticket.submit_count+1
    if submitter_id:
        try:
            submitter = Submitter.objects.get(submitter_id=submitter_id)
            data_ticket.submitter = submitter
        except ObjectDoesNotExist:
            return JsonResponse({'error': 'Submitter not found'}, status=404)
    assigned_admin_id = data.get('assigned_admin_id')
    if assigned_admin_id:
        try:
            assigned_admin = Admin.objects.get(admin_id=assigned_admin_id)
            data_ticket.assigned_admin = assigned_admin
        except ObjectDoesNotExist:
            return JsonResponse({'error': 'Admin not found'}, status=404)
    data_ticket.status = data.get('status', data_ticket.status)
    data_ticket.save()
    return JsonResponse({'message': 'DataTicket updated successfully', 'data': {
        'ticket_id': data_ticket.ticket_id,
        'ticket_type': data_ticket.ticket_type,
        'question': data_ticket.question,
        'answer': data_ticket.answer,
        'submitter_id': data_ticket.submitter_id,
        'submit_time': data_ticket.submit_time.isoformat(),
        'submit_count': data_ticket.submit_count,
        'assigned_admin_id': data_ticket.assigned_admin_id,
        'status': data_ticket.status,
    }})


@csrf_exempt
@require_http_methods(["DELETE"])
def delete_data_ticket(request, ticket_id):
    try:
        data_ticket = DataTicket.objects.get(ticket_id=ticket_id)
    except ObjectDoesNotExist:
        return JsonResponse({'error': 'DataTicket not found'}, status=404)
    data_ticket.delete()
    return JsonResponse({'message': 'DataTicket deleted successfully'})



class DataTicketListView1(generics.ListCreateAPIView):
    serializer_class = DataTicketSerializer
    pagination_class = StandardResultsSetPagination

    def get_queryset(self):
        submitter_id = self.request.query_params.get('submitter_id', None)
        print(submitter_id)
        if not submitter_id:
            return DataTicket.objects.none()
        queryset = DataTicket.objects.filter(
            assigned_admin=submitter_id,
            status='待处理'
        ).exclude(
            flag=1
        )
        keyword = self.request.query_params.get('keyword', None)
        if keyword:
            queryset = queryset.filter(
                Q(ticket_type__icontains=keyword) |
                Q(question__icontains=keyword) |
                Q(answer__icontains=keyword) |
                Q(status__icontains=keyword)
            )
        return queryset.distinct()
    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        if not queryset.exists():
            return Response({'message': '没有数据'}, status=status.HTTP_200_OK)
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

#驳回状态
@csrf_exempt  #仅用于测试，生产环境中应使用适当的CSRF保护
@require_http_methods(["PUT"])
def reject_data_ticket(request, ticket_id):
    try:
        data_ticket = DataTicket.objects.get(ticket_id=ticket_id)
    except ObjectDoesNotExist:
        return JsonResponse({'error': 'DataTicket not found'}, status=404)
    data_ticket.status = '驳回'
    data_ticket.save()
    return JsonResponse({'message': 'DataTicket status updated to "驳回" successfully', 'data': {
        'ticket_id': data_ticket.ticket_id,
        'status': data_ticket.status,
    }})



@csrf_exempt
@require_http_methods(["PUT"])
def re_data_ticket(request, ticket_id):
    try:
        data_ticket = DataTicket.objects.get(ticket_id=ticket_id)
    except DataTicket.DoesNotExist:
        return JsonResponse({'error': 'DataTicket not found'}, status=404)
    question = data_ticket.question
    answer = data_ticket.answer
    print(1)
    if not answer:
        return JsonResponse({'error': 'Answer is required'}, status=400)
    print(1)
    data_ticket.status = '已处理'
    data_ticket.save()
    assigned_admin = data_ticket.assigned_admin
    print(assigned_admin)
    if not assigned_admin:
        return JsonResponse({'error': 'Assigned admin not found'}, status=404)
    scenic_spot = ScenicSpot.objects.filter(responsible_admin=assigned_admin).first()
    print(scenic_spot)
    if not scenic_spot:
        return JsonResponse({'error': 'Scenic spot not found for the assigned admin'}, status=404)
    qa_pair, created = QaPair.objects.update_or_create(
        jq=scenic_spot,
        question=question,
        defaults={'answer': answer, 'last_operation_time': timezone.now()}
    )
    if created:
        scenic_spot.qa_count += 1
        scenic_spot.save()

    return JsonResponse({
        'message': 'DataTicket status updated and QaPair saved successfully',
        'data': {
            'ticket_id': data_ticket.ticket_id,
            'status': data_ticket.status,
        }
    })

def get_scenic_spot_types(request):
    scenic_spots = ScenicSpot.objects.select_related('responsible_admin').all()
    data = []
    for spot in scenic_spots:
        admin_id = spot.responsible_admin.admin_id if spot.responsible_admin else "未分配"
        data.append({
            "jq_id": spot.jq_id,
            "jq_name": spot.jq_name,
            "jq_type": spot.jq_type,
            "responsible_admin": admin_id,
        })
        print(data)
    return JsonResponse(data, safe=False)


def get_scenic_spot_types1(request):
    scenic_spots = ScenicSpot.objects.all().values_list('jq_id', flat=True)
    scenic_spot_ids = list(scenic_spots)
    print(scenic_spot_ids)
    return JsonResponse({'scenic_spot_ids': scenic_spot_ids}, safe=False)
@csrf_exempt
@require_http_methods(["POST"])
def workflow(request):
    # print(1)
    #
    # # 解析请求体中的数据
    # try:
    #     data = json.loads(request.body)
    #     destination_city = data.get('parameters', {}).get('destination_city', '')
    #     scenic_spot_count = data.get('parameters', {}).get('scenicSpotCount', '')
    #     arrival_date = data.get('parameters', {}).get('arrivalDate', '')
    # except json.JSONDecodeError:
    #     return JsonResponse({"code": 1, "msg": "Invalid JSON data"}, status=400)
    #
    # # 设置请求的 URL 和头部
    # url = 'https://api.coze.cn/v1/workflow/run'
    # headers = {
    #     'Authorization': 'Bearer pat_dbZ1Wj6rlWMhgaJapB6HzmyJSv3mwQyi3hzVmcgcKfrTQ7RuInR0IItKXlAaq34M',
    #     'Content-Type': 'application/json'
    # }
    # payload = {
    #     "parameters": {
    #         "destination_city": destination_city,
    #         "start_date": arrival_date,
    #         "scenicspot": scenic_spot_count
    #     },
    #     "workflow_id": "7458921199965077567"
    # }
    # print(1)
    # print(payload)
    # try:
    #     response = requests.post(url, headers=headers, json=payload)
    #     response.raise_for_status()  # 检查请求是否成功
    #     print(response.text)
    #     return JsonResponse({"code": 0, "msg": "Request successful", "data": response.json()}, safe=False)
    # except requests.RequestException as e:
    #
    #     error_msg = f"Failed to fetch data from {url}. Please check the URL and your network connection. Error: {str(e)}"
    #     return JsonResponse({"code": 2, "msg": error_msg}, status=500)
    data = json.loads(request.body)
    jq_name = data.get('parameters', {}).get('scenicSpotCount', '')
    if not jq_name:
        return JsonResponse({'code': 0, 'msg': 'Missing jq_name parameter'}, status=400)
    try:
        scenic_spot = ScenicSpot.objects.get(jq_name=jq_name)
    except ScenicSpot.DoesNotExist:
        return JsonResponse({'code': 1, 'msg': 'Scenic spot not found'}, status=404)
    try:
        attraction_info = TouristAttraction.objects.get(jq_name=scenic_spot)
    except TouristAttraction.DoesNotExist:
        return JsonResponse({'code': 1, 'msg': 'Tourist attraction info not found'}, status=404)
    response_data = {
        'code': 2,
        'msg': 'Success',
        'data': {
            'jq_intro': attraction_info.jq_intro,
            'jq_what': attraction_info.jq_what,
            'jq_culture': attraction_info.jq_culture,
            'jq_around': attraction_info.jq_around,
            'jq_vehicle': attraction_info.jq_vehicle,
            'jq_address': attraction_info.jq_address,
            'jq_restaurant': attraction_info.jq_restaurant,
            'jq_food': attraction_info.jq_food,
            'contents': attraction_info.contents,
        }
    }
    return JsonResponse(response_data, safe=False)

import pandas as pd


@csrf_exempt
@require_http_methods(["POST"])
def export_data(request):
    # 获取请求中的数据
    data = json.loads(request.body)
    jq_name = data.get('parameters', {}).get('scenicSpotCount', '')
    if not jq_name:
        return JsonResponse({'code': 0, 'msg': 'Missing jq_name parameter'}, status=400)
    try:
        scenic_spot = ScenicSpot.objects.get(jq_name=jq_name)
    except ScenicSpot.DoesNotExist:
        return JsonResponse({'code': 1, 'msg': 'Scenic spot not found'}, status=404)
    try:
        attraction_info = TouristAttraction.objects.get(jq_name=scenic_spot)
    except TouristAttraction.DoesNotExist:
        return JsonResponse({'code': 1, 'msg': 'Tourist attraction info not found'}, status=404)
    data_to_export = f"""景点介绍：
{attraction_info.jq_intro}

景点详情：
{attraction_info.jq_what}

文化背景：
{attraction_info.jq_culture}

周边信息：
{attraction_info.jq_around}

交通信息：
{attraction_info.jq_vehicle}

地址信息：
{attraction_info.jq_address}

餐厅信息：
{attraction_info.jq_restaurant}

美食信息：
{attraction_info.jq_food}

详细内容：
{attraction_info.contents}
"""
    response = HttpResponse(data_to_export, content_type='text/plain')
    response['Content-Disposition'] = 'attachment; filename="exported_data.txt"'
    return response


# def transform_data(raw_data):
#     elements = {
#         "nodes": [],
#         "edges": []
#     }
#
#     for item in raw_data:
#         start_node = {
#             "data": {
#                 "id": item["p"]["start"]["elementId"],
#                 "label": item["p"]["start"]["properties"]["name"]
#             }
#         }
#         end_node = {
#             "data": {
#                 "id": item["p"]["end"]["elementId"],
#                 "label": item["p"]["end"]["properties"]["name"]
#             }
#         }
#         elements["nodes"].append(start_node)
#         elements["nodes"].append(end_node)
#
#         edge = {
#             "data": {
#                 "id": item["p"]["segments"][0]["relationship"]["elementId"],
#                 "source": item["p"]["start"]["elementId"],
#                 "target": item["p"]["end"]["elementId"]
#             }
#         }
#         elements["edges"].append(edge)
#
#     return elements


def knowledge_graph(request):
    # json_file_path = 'static/1.json'
    # with open(json_file_path, 'r', encoding='utf-8') as file:
    #     raw_data = json.load(file)
    # transformed_data = transform_data(raw_data)
    # return JsonResponse(transformed_data, safe=False)
    json_file_path = 'static/1.json'
    with open(json_file_path, 'r', encoding='utf-8') as file:
        data = json.load(file)
    return JsonResponse(data, safe=False)